import { defineStore } from "pinia";
import StudentApi from "@/api/student";

export const useStudentStore = defineStore(
  "student",
  () => {
    const personnelIds = ref<number[]>([]); // 绑定的学生列表
    const curPersonnelId = ref<number>(-1); // 当前选择的人员id
    const studentInfos = ref<any>([]); // 学生信息列表
    const curStudentInfo = ref({}); // 当前选择的学生信息
    const addPersonnelIds = async (personnelInfos: any) => {
      personnelIds.value = personnelInfos.map((item) => {
        return item.personnelId;
      });
      studentInfos.value = personnelInfos;
      curPersonnelId.value = personnelIds.value[0];
      curStudentInfo.value = studentInfos.value[0];
    };
    const setPersonnelIds = async (personnelId: number) => {
      if (!personnelIds.value.includes(personnelId))
        personnelIds.value.push(personnelId);
      const res = await StudentApi.getPersonnels();
      if (res) {
        studentInfos.value = res;
        curStudentInfo.value =
          res.find((item) => item.personnelId === personnelId) || {};
      }
    };
    const setCurpersonnelId = (personnelId: number) => {
      curPersonnelId.value = personnelId;
      if (studentInfos.value.length > 0) {
        curStudentInfo.value =
          studentInfos.value.find((item) => item.personnelId === personnelId) ||
          {};
      }
    };
    const removeStudentInfo = () => {
      uni.removeStorageSync("personnelIds");
      uni.removeStorageSync("curPersonnelId");
      uni.removeStorageSync("studentInfos");
      uni.removeStorageSync("curStudentInfo");
    };

    return {
      personnelIds,
      setPersonnelIds,
      curPersonnelId,
      studentInfos,
      curStudentInfo,
      setCurpersonnelId,
      removeStudentInfo,
      addPersonnelIds,
    };
  },
  {
    persist: true,
  },
);
